import { BasePlayer } from './BasePlayer';
import { FactoryToken } from '../../../framework/common/factory/AbstractFactory';
import { PlayerType } from '../../const/TokenConst';
import { PlayerMgr } from '../../mgr/PlayerMgr';
import { RoleType } from '../../const/RoleType';
import { GameMgr } from '../../mgr/GameMgr';

/**
 * 玩家参与游戏
 */
@FactoryToken(PlayerType.GamePlayer)
export class GamePlayer extends BasePlayer {
    constructor() {
        super();
    }

    public start(): void {
        super.start();
        console.log('(Server) GamePlayer start');
        this.entity!.enableDamage = true;
        this.entity!.hp = 100;
        this.entity!.maxHp = 100;
        this.roleType = RoleType.Ghost;
    }

    public update(delta: number): void {
        super.update(delta);
    }

    protected btnPressAction0(event: GameInputEvent): void {
        super.btnPressAction0(event);
        console.log('(Server) GamePlayer btnPressAction0');
        if (this.entity?.hp) {
            const { raycast } = event;
            if (raycast.hit && raycast.hitEntity && raycast.hitEntity.player) {
                const player = PlayerMgr.instance.getPlayer(
                    raycast.hitEntity.player.userId
                );
                if (player?.entity?.enableDamage) {
                    const { entity } = player;
                    entity.hurt(10);
                    entity.velocity.addEq(raycast.direction);
                    if (this.roleType === RoleType.Pumpkin) {
                        entity.velocity.addEq(raycast.direction);
                    }
                }
            }
        }
    }

    public onDie(event: GameDieEvent): void {
        super.onDie(event);
        console.log('(Server) GamePlayer onDie');
        if (this.roleType === RoleType.Pumpkin) {
            // 原地生成南瓜
            GameMgr.instance.createPumpkin(
                this.entity?.position as GameVector3
            );
        }
        this.roleType = RoleType.Ghost;
        setTimeout(() => {
            if (this.entity) {
                this.entity.hp = 100;
            }
        }, 5000);
    }

    public get roleType(): RoleType {
        return super.roleType;
    }

    public set roleType(value: RoleType) {
        super.roleType = value;
        switch (value) {
            case RoleType.Ghost:
                this.entity?.player.setSkinByName('幽灵');
                break;
            case RoleType.Pumpkin:
                this.entity?.player.setSkinByName('转生南瓜');
                break;
        }
    }
}
